﻿using Ldt.DataEngine.RuleAssemble;
using LdtJudge.DataEngine.Common.CommHelp;
using LdtJudge.DataEngine.Common.MoneyAssemble;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.Collection;
using LdtJudge.DataEngine.Model.ElmentModel;
using LdtJudge.DataEngine.Model.Personnel;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using LdtJudge.DataEngine.PersonnelAnalysis.PersonnelBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace LdtDataEngin.ModuleDetail.BaseModule.PersonnelBase
{
    public class PersonnelAnalysisBase
    {

        /// <summary>
        /// 人员信息集合
        /// </summary>
        public IList<ElementSpokeName> spokenamelist { get; set; }
        /// <summary>
        /// 根据将文本中代称信息转换为人员信息
        /// </summary>
        /// <param name="ListName"></param>
        /// <param name="originalText"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        public string ReplaceShortNameToFullName(IList<ElementSpokeName> ListName, string originalText, string flag = "")
        {
            originalText = originalText.Replace("原告方", "**1");
            originalText = originalText.Replace("被告方", "**2");
            foreach (ElementSpokeName item in ListName)
            {
                if (!string.IsNullOrEmpty(item.ES_ShortName))
                {

                    //originalText = originalText.Replace(item.ES_ShortName, item.ES_FullName);
                }
            }
            spokenamelist = ListName;
            originalText = dealPre(originalText);
            string newOriginalText = FormatOriginalText(originalText, ListName);

            try
            {
                //做被一到被九的替换
                var accusedPeople = ListName.Where(a => a.ES_SuitDrgreeID == "90").ToList();
                string name = string.Empty;
                string _roleCHNNum = string.Empty;
                string _roleintNum = string.Empty;
                string replacecontent = string.Empty;
                ChnNumFormat cnf = new ChnNumFormat();
                foreach (var s in accusedPeople)
                {
                    name += s.ES_FullName + "|";
                    if ((Convert.ToInt32(s.ES_RoleIndex) < 10))
                    {
                        _roleCHNNum += cnf.NumToChn(s.ES_RoleIndex.ToString());
                        _roleintNum += s.ES_RoleIndex;
                    }
                    else
                    {
                        _roleCHNNum = "一二三四五六七八九十";
                        _roleintNum = "\\d";
                    }
                }
                replacecontent = _roleCHNNum + "、,，" + _roleintNum;
                string beiReg = RuleParseClass.GerParseReg("RIU1910211531320001")[0];
                if (!string.IsNullOrEmpty(name))
                {
                    beiReg = beiReg.Replace("(@{Name})", name.Remove(name.Length - 1, 1));
                    beiReg = beiReg.Replace("(@{Name1})", replacecontent);
                }
                Regex bei = new Regex(beiReg);
                string rpReg = RuleParseClass.GerParseReg("RIU1910281149210001")[0];
                Regex rp = new Regex(rpReg);
                string chineseNumber = "一二三四五六七八九123456789";
                var accused = ListName.Where(a => a.ES_SuitDrgreeID == "90").OrderBy(a => a.ES_RoleIndex).ToList();
                Match m = bei.Match(newOriginalText);
                #region 进行提取
                while (m != null && m.Value != string.Empty && accused.Count > 0)//&& accused.Count>0 ljx 2017-07-21添加条件判断！ 防止死循环
                {
                    string r = rp.Replace(m.Value, "");
                    //只出现一次 比如 被一 被告一的替换
                    if (r.ToArray().Count() == 1)
                    {
                        char cnum = m.Value.ToArray().Last().ToString().ToCharArray().First();
                        int num = chineseNumber.ToArray().ToList().FindIndex(a => a == cnum);
                        if ((num % 9 + 1.0) <= accused.Count)
                        {
                            string s = newOriginalText.Substring(m.Index, m.Value.Length);
                            newOriginalText = newOriginalText.Remove(m.Index, m.Length); //删除匹配到的内容
                            if (string.IsNullOrEmpty(flag))
                            {
                                var accuse = accused.FirstOrDefault(a => int.Parse(a.ES_RoleIndex) == (num % 9 + 1.0));
                                if (accuse != null)
                                {
                                    newOriginalText = newOriginalText.Insert(m.Index, "被告" + accuse.ES_FullName);
                                }
                            }
                            else
                            {
                                var accuse = accused.FirstOrDefault(a => int.Parse(a.ES_RoleIndex) == (num % 9 + 1.0));
                                if (accuse != null)
                                {
                                    newOriginalText = newOriginalText.Insert(m.Index, accuse.ES_FullName);
                                }
                            }
                        }
                        else
                        {
                            if (accused.Count > 9)
                            {
                                string s = newOriginalText.Substring(m.Index, m.Value.Length);
                                newOriginalText = newOriginalText.Remove(m.Index, m.Length); //删除匹配到的内容
                                if (string.IsNullOrEmpty(flag))
                                {
                                    var accuse = accused.FirstOrDefault(a => int.Parse(a.ES_RoleIndex) == (num % 9 + 1.0));
                                    if (accuse != null)
                                    {
                                        newOriginalText = newOriginalText.Insert(m.Index, "被告" + accuse.ES_FullName);
                                    }
                                }
                                else
                                {
                                    var accuse = accused.FirstOrDefault(a => int.Parse(a.ES_RoleIndex) == (num % 9 + 1.0));
                                    if (accuse != null)
                                    {
                                        newOriginalText = newOriginalText.Insert(m.Index, accuse.ES_FullName);
                                    }
                                }
                            }
                        }
                    }
                    //出现多次 如 被一、二、三的替换
                    else
                    {
                        string replaceText = "";
                        string[] result = r.Split(new char[] { '、', ',', ',' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var it in result)
                        {
                            try
                            {
                                int num = (int)int.Parse(LdtMoneyFormat.DecodeNumberCn(it.ToString()).ToString());
                                num -= 1;
                                if (num <= accused.Count)
                                {
                                    if (string.IsNullOrEmpty(flag))
                                    {
                                        replaceText = replaceText + "被告" + accused[num].ES_FullName + "、";

                                    }
                                    else
                                    {
                                        replaceText = replaceText + accused[num].ES_FullName + "、";

                                    }
                                }
                            }
                            catch (Exception err)
                            {
                                replaceText = replaceText + it;

                            }
                        }
                        newOriginalText = newOriginalText.Remove(m.Index, m.Length);
                        //判断传进来的是被告三、还是被告三、四
                        if (result.Length == 1)
                        {
                            newOriginalText = newOriginalText.Insert(m.Index, replaceText);
                        }
                        else
                        {
                            newOriginalText = newOriginalText.Insert(m.Index, replaceText.Remove(replaceText.Length - 1, 1));
                        }
                    }

                    m = bei.Match(newOriginalText);
                }
                #endregion
            }
            catch (Exception err)
            {

            }
            string regPattern = string.Empty;
            var query = from item in ListName
                        where !string.IsNullOrWhiteSpace(item.ES_SuitDegreeName) && (!string.IsNullOrWhiteSpace(item.ES_FullName) || !string.IsNullOrWhiteSpace(item.ES_ShortName))
                        group item by item.ES_SuitDegreeName into g
                        select new { Group = g.Key, Member = g };
            string Renyuan = RuleParseClass.GerParseReg("RIU1910211532260001")[0];
            foreach (var item in query)
            {
                string allFullName = string.Join("|", item.Member.Select(x => x.ES_FullName).ToList<string>());
                string allShortName = string.Join("|", item.Member.Select(x => x.ES_FullName).ToList<string>());
                allFullName += (allShortName == string.Empty) ? "" : "|" + allShortName;
                regPattern += (regPattern == "") ? "" : "|";
                regPattern += Renyuan.Replace("@{Name}", item.Group).Replace("@{Name_a}", allFullName.Replace("*", "\\*"));
            }
            //替换值文本集合0
            Dictionary<string, string> replaceDict = new Dictionary<string, string>();

            MatchCollection matchArr = Regex.Matches(newOriginalText, regPattern);
            if (!string.IsNullOrEmpty(regPattern))
            {
                List<Tuple<int, int, int>> replacedList = new List<Tuple<int, int, int>>();//记录已替换的位置
                for (int z = matchArr.Count - 1; z >= 0; z--)
                {
                    Match match = matchArr[z];
                    string extractValue = match.Value;
                    string extrname = extractValue.Replace("原告", "").Replace("、", "").Replace(",", "").Trim();
                    if (extractValue == "原告" || extractValue.IndexOf("原告") == -1 || extrname == null || LdtMoneyFormat.DecodeNumberCn(extrname) == 1)
                    {
                        //处理匹配到 比如三被告共同的情况 此情况下被告不做替换 第一、二被告----第一被告、第二被告
                        try
                        {
                            if (newOriginalText.Length >= match.Index && match.Index - 2 > -1)
                            {
                                string last = newOriginalText.Substring(match.Index - 2, 2);//取名称前2个字
                                if (Regex.IsMatch(RuleParseClass.GerParseReg("RIU1910211530430001")[0], last))
                                {
                                    continue;
                                }
                            }
                        }
                        catch (Exception err)
                        {

                        }
                        string replaceValue = string.Empty;
                        List<string> queryperson = new List<string>();
                        if (replaceDict.ContainsKey(extractValue))
                        {
                            replaceValue = replaceDict[extractValue];
                        }
                        else
                        {
                            //根据代称获取人员信息集合
                            IList<ElementSpokeName> matchList2 = GetMatchSpokeManByRoleName(ListName, extractValue.Replace("、", ""));
                            if (string.IsNullOrEmpty(flag))
                            {
                                queryperson = (from person in matchList2
                                               where (person.ES_SuitDegreeName != "" || person.ES_FullName != "")
                                               select person.ES_SuitDegreeName + person.ES_FullName).Distinct().ToList();
                            }
                            else
                            {
                                queryperson = (from person in matchList2
                                               where (person.ES_SuitDegreeName != "" || person.ES_FullName != "")
                                               select person.ES_FullName).Distinct().ToList();
                            }
                            replaceValue = String.Join("、", queryperson);
                            var next = matchArr.Cast<Match>().SingleOrDefault(a => a.Index == match.Index + match.Length);
                            //兼容人员替换后无顿号的情况
                            if (extractValue.EndsWith("、") && next != null)
                            {
                                replaceDict.Add(extractValue, replaceValue + "、");
                            }
                            else if (extractValue.EndsWith("、") && next == null)
                            {
                                replaceDict.Add(extractValue, replaceValue);
                            }
                            else
                            {
                                replaceDict.Add(extractValue, replaceValue);
                            }
                        }
                        try
                        {
                            string test = newOriginalText.Substring(match.Index + match.Length);
                            bool isreplace = true;
                            foreach (var sp in ListName)
                            {
                                if (sp != null && sp.ES_ShortName != null)
                                {
                                    if ((replaceValue.IndexOf(sp.ES_ShortName) > 0 && test.StartsWith(sp.ES_ShortName)) || replaceValue == "")
                                    {
                                        isreplace = false;
                                        break;
                                    }
                                }
                            }
                            if (isreplace)
                            {
                                newOriginalText = newOriginalText.Remove(match.Index, match.Length);
                                newOriginalText = newOriginalText.Insert(match.Index, replaceValue);
                            }
                        }
                        catch (Exception err)
                        {
                        }
                        var it = replacedList.LastOrDefault();
                        //判断上次替换之前名称是否连接
                        if (it != null)
                        {
                            if (it.Item1 == match.Index + match.Length)
                            {
                                if (!string.IsNullOrEmpty(replaceValue))
                                {
                                    if (newOriginalText.ToArray()[match.Index + replaceValue.Length - 1] != '、')
                                    {
                                        newOriginalText = newOriginalText.Insert(match.Index + replaceValue.Length, "、");
                                    }
                                }

                            }
                        }
                        if (!replaceValue.EndsWith("、"))
                        {
                            //记录上次替换的位置 防止原被告这种直接连接的替换后无顿号
                            Tuple<int, int, int> tp = new Tuple<int, int, int>(match.Index, match.Length, replaceValue.Length);
                            replacedList.Add(tp);
                        }
                    }

                }
            }

            return newOriginalText.Replace("**1", "原告方").Replace("**2", "被告方").Replace("**3", "原、被告");
        }

        /// <summary>
        /// 返回匹配到的人员集合&*
        /// </summary>
        /// <param name="relatList">匹配人员集合</param>
        /// <param name="proxyRoleName">代理角色</param>
        /// <returns>匹配到的人员集合</returns>
        public IList<ElementSpokeName> GetMatchSpokeManByRoleName(IList<ElementSpokeName> relatList, string proxyRoleName)
        {

            if (relatList.Any(a => a.ES_FullName == proxyRoleName))
            {
                return new List<ElementSpokeName>() { relatList.First(a => a.ES_FullName == proxyRoleName) };
            }
            #region 处理二被告 各被告这种格式
            ChnNumFormat chn = new ChnNumFormat();
            string cnReg = RuleParseClass.GerParseReg("RIU1910211532140001")[0];
            string cncount = Regex.Match(proxyRoleName, cnReg).Value;
            if (cncount == "两") cncount = "二";
            if (cncount == "各")
            {
                return relatList.Where(a => a.ES_SuitDrgreeID == "90").ToList();
            }
            if (cncount == "二" || cncount == "三" || cncount == "四" || cncount == "五" || cncount == "六")
            {
                if (chn.NumToChn(this.spokenamelist.Where(a => a.ES_SuitDrgreeID == "90").Count().ToString()) == cncount)
                {
                    string roleRegjuese = RuleParseClass.GerParseReg("RIU1910211532040001")[0];
                    Regex reg = new Regex(roleRegjuese);
                    return relatList.Where(a => a.ES_SuitDrgreeID == "90").ToList();
                }
                //else
                //{
                //    return new List<ElementSpokeName>();
                //}
            }
            #endregion

            #region 多人员匹配方案
            List<ElementSpokeName> spokeList = new List<ElementSpokeName>();
            string roleReg = RuleParseClass.GerParseReg("RIU1910211532040001")[0];
            IList<double> roleIndexList = new List<double>();
            if (proxyRoleName.IndexOf("、") > 0 && !proxyRoleName.Contains("原"))
            {
                List<string> spokemans = MultiSpokeManParse.Parse(proxyRoleName);
                foreach (string spoker in spokemans)
                {
                    List<ElementSpokeName> returnlist = new List<ElementSpokeName>();
                    returnlist = GetSpokerManByOridinalAndRoleName(relatList, spoker);
                    if (returnlist.Count != 0)
                    {
                        if (spokeList.Contains(returnlist[0]))
                        {
                            if (returnlist.Count > 1)
                            {
                                spokeList.Add(returnlist[1]);
                            }
                        }
                        else
                        {
                            spokeList.Add(returnlist[0]);
                        }
                    }
                }
            }
            else
            {
                string roleNamejuese = Regex.Replace(proxyRoleName, roleReg, "");
                List<char> roleindex = Regex.Match(proxyRoleName, roleReg).ToString().ToArray().ToList();
                if (proxyRoleName.StartsWith("第") && roleindex.Count > 1)
                {
                    foreach (char item in roleindex)
                    {
                        double roleindexNum = LdtMoneyFormat.DecodeNumberCn(item.ToString());
                        if (roleindexNum != 0)
                        {
                            List<ElementSpokeName> spkerman = relatList.Where(a => a.ES_SuitDegreeName == roleNamejuese).ToList();
                            if (spkerman.Count > (roleindexNum - 1))
                            {
                                spokeList.Add(spkerman[Convert.ToInt32(roleindexNum - 1)]);
                            }
                        }
                    }
                }
                else
                {
                    spokeList = GetSpokerManByOridinalAndRoleName(relatList, proxyRoleName);
                }
            }
            #endregion
            return spokeList;
        }

        /// <summary>
        /// 返回匹配到的人员集合根据代理人信息
        /// </summary>
        /// <param name="elementSpokeList">发言人集合</param>
        /// <param name="viewSourdatModleList">优选结果对象集合</param>
        /// <param name="agentSourceTxt">共同委托代理人提取文本</param>
        /// <param name="agent">共同委托代理人信息</param>
        /// <returns>匹配到的人员集合</returns>
        public List<ElementSpokeName> GetMatchSpokeManByagentSourceTxt(List<ElementSpokeName> elementSpokeList, List<DataModel> viewSourdatModleList, string agentSourceTxt, DataModel agent)
        {
            //案件信息要素中心 / 诉讼参与人 / 当事人详情 / 诉讼代理人 / 详情
            //先获取父级诉讼代理人ID再获取当事人详情ID
            var parent = viewSourdatModleList.Where(x => x.ID == agent.ParentId).FirstOrDefault();
            if (parent != null)
                parent = viewSourdatModleList.Where(x => x.ID == parent.ParentId).FirstOrDefault();
            //获取当事人详情下AttributesList下sourceList中IsCheck=1的savevalue值
            string name = parent?.AttributesList[0]?.sourceList.Where(x => x.IsCheck == "1")?.FirstOrDefault()?.SaveValue;
            //根据名称获取当事人的索引
            var info = elementSpokeList.Where(x => x.ES_FullName == name).FirstOrDefault();
            int index = Convert.ToInt32(info?.ES_RoleIndex);
            string roleName = info.ES_SuitDegreeName;
            List<ElementSpokeName> personList = new List<ElementSpokeName>();
            if (index > 0)
            {
                string ptReg = RuleParseClass.GerParseReg("RIU1910211531480001")[0];
                var matchsLists = Regex.Matches(agentSourceTxt, ptReg);
                var roleindexNum = Convert.ToInt32(LdtMoneyFormat.DecodeNumberCn(matchsLists[0].ToString()));               
                for (int i = roleindexNum; i > 0; i--)
                {
                    personList.Add(elementSpokeList.Where(x => x.ES_SuitDegreeName == roleName && x.ES_RoleIndex == i.ToString()).FirstOrDefault());
                }
            }
            return personList;
        }


        /// <summary>
        /// 通过rolename找人  返回匹配的集合
        /// </summary>
        /// <param name="relatList"></param>
        /// <param name="proxyRoleName"></param>
        /// <returns></returns>
        public virtual List<ElementSpokeName> GetSpokerManByOridinalAndRoleName(IList<ElementSpokeName> relatList, string proxyRoleName)
        {
            List<ElementSpokeName> spokeList = new List<ElementSpokeName>();
            string ptReg = RuleParseClass.GerParseReg("RIU1910211531480001")[0];
            string roleReg = RuleParseClass.GerParseReg("RIU1910211532040001")[0];
            string roleName = Regex.Replace(proxyRoleName, roleReg, "");
            IList<ElementSpokeName> roleList = relatList.Where(a => a.ES_SuitDegreeName.Contains(roleName)).ToList();
            if (roleList.Count > 0)
            {
                List<char> rolenum = Regex.Match(proxyRoleName, ptReg).ToString().ToArray().ToList();
                if (rolenum.Count > 0)
                {
                    double roleindexNum = 0;
                    for (int i = 0; i < rolenum.Count; i++)
                    {
                        roleindexNum += LdtMoneyFormat.DecodeNumberCn(rolenum[i].ToString());
                    }
                    roleList = roleList.Where(a => a.ES_RoleIndex == roleindexNum.ToString() && a.ES_SuitDegreeName.Contains(roleName)).ToList();
                }
            }
            if (spokeList.Count == 0)
            {

                string role = Regex.Replace(proxyRoleName, roleReg, "");
                var matchsLists = Regex.Matches(proxyRoleName, ptReg);
                foreach (var item in matchsLists)
                {
                    List<char> rolenum = item.ToString().ToArray().ToList();
                    if (rolenum.Count > 0)
                    {
                        double roleindexNum = 0;
                        for (int i = 0; i < rolenum.Count; i++)
                        {
                            roleindexNum += LdtMoneyFormat.DecodeNumberCn(rolenum[i].ToString());
                        }
                        var spokerman = relatList.Where(a => a.ES_RoleIndex == roleindexNum.ToString() && a.ES_SuitDegreeName.Contains(role)).FirstOrDefault<ElementSpokeName>();

                        if (spokerman != null)
                        {
                            spokeList.Add(spokerman);
                        }
                        if (relatList.Where(a => a.ES_SuitDegreeName.Contains(role)).Count() == Convert.ToInt32(roleindexNum) && roleindexNum != 0 && matchsLists.Count == 1 && proxyRoleName.IndexOf(item.ToString()) == 0)
                        {
                            spokeList = relatList.Where(a => a.ES_SuitDegreeName.Contains(role)).ToList();
                        }
                        else
                        {
                            try
                            {
                                if (proxyRoleName.IndexOf(item.ToString()) == 0)
                                {
                                    spokeList = relatList.Where(a => a.ES_SuitDegreeName.Contains(role) && (a.ES_RoleIndex == roleindexNum.ToString() || a.ES_RoleIndex == (roleindexNum + 1).ToString())).ToList();
                                }
                            }
                            catch (Exception)
                            {


                            }
                        }


                    }
                }

            }
            if (spokeList.Count == 0)
            {
                var mspoke = from spoke in relatList
                             where (spoke.ES_SuitDegreeName == proxyRoleName)
                             || (spoke.ES_ShortName == proxyRoleName)
                             || (spoke.ES_ShortName == proxyRoleName)
                             select spoke;
                spokeList = mspoke.ToList<ElementSpokeName>();
                //if (proxyRoleName == "被告" && spokeList.Count != 1)
                //{
                //    spokeList = new List<ElementSpokeName>();
                //}
                //if (proxyRoleName == "原告" && spokeList.Count != 1)
                //{
                //    spokeList = new List<ElementSpokeName>();
                //}

            }

            return spokeList;
        }
        /// <summary>
        /// 在人员名称替换前置处理
        /// </summary>
        /// <param name="originalText">原文信息</param>
        public string dealPre(string originalText)
        {
            string fReg = RuleParseClass.GerParseReg("RIU1910211530500001")[0];
            Regex f = new Regex(fReg);
            originalText = f.Replace(originalText, "原告被告");//处理原被告无法识别的问题
            return originalText;
        }

        /// <summary>
        /// 原文格式化
        /// </summary>
        /// <param name="originalText"></param>
        /// <returns></returns>
        public string FormatOriginalText(string originalText, IList<ElementSpokeName> ListName)
        {
            List<ElementSpokeName> result = ListName.Where(a => a.ES_SuitDrgreeID == "90").ToList();
            string newOriginalText = originalText;
            IList<string> existMatch = new List<string>();
            string fReg = RuleParseClass.GerParseReg("RIU1910251718060001")[0];
            Regex f = new Regex(fReg);

            if (ListName.Where(a => a.ES_SuitDrgreeID == "90").ToList().Count == 1 && ListName.Where(a => a.ES_SuitDrgreeID == "89").ToList().Count == 1)
            {
                newOriginalText = f.Replace(originalText, "原告被告");
            }
            else
            {
                newOriginalText = f.Replace(originalText, "**3");
            }
            //处理 "被告一" 写为 "被告 一"的时候名称替换的问题
            Regex space = new Regex("\\s");
            newOriginalText = space.Replace(newOriginalText, "");
            string oMatchCollReg = "被告([一二三四五六七八九十]+)至(被告|原告)?([一二三四五六七八九十]+)";
            MatchCollection oMatchColl = Regex.Matches(newOriginalText, oMatchCollReg);
            foreach (Match oMatch in oMatchColl)
            {
                if (existMatch.Contains(oMatch.Value))
                    continue;
                else
                    existMatch.Add(oMatch.Value);
                IList<string> ChnNumbList = new List<string>();
                string startIndex = oMatch.Groups[1].Value;
                string endIndex = oMatch.Groups[2].Value;
                Regex reg = new Regex("[一二三四五六七八九十]+");
                if (!reg.IsMatch(endIndex))
                {
                    endIndex = oMatch.Groups[3].Value;
                }
                int startInt = Convert.ToInt32(LdtMoneyFormat.DecodeNumberCn(startIndex));
                int endInt = Convert.ToInt32(LdtMoneyFormat.DecodeNumberCn(endIndex));

                ChnNumFormat ChnNumFormatObj = new ChnNumFormat();
                List<string> rolelist = new List<string>();
                for (int i = startInt; i <= endInt; i++)
                {
                    string ChnNumbStr = ChnNumFormatObj.NumToChn(i.ToString());
                    var name = result.Where(a => int.Parse(a.ES_RoleIndex) == i).ToList();
                    string rolename = string.Empty;
                    foreach (var item in name)
                    {
                        rolename = "被告" + item.ES_FullName;
                    }
                    if (!string.IsNullOrWhiteSpace(rolename))
                    {
                        rolelist.Add(rolename);
                    }
                    ChnNumbList.Add(ChnNumbStr);
                }
                string replaceStr = string.Join<string>("、", rolelist);
                replaceStr = replaceStr.Substring(0, replaceStr.Length);
                newOriginalText = Regex.Replace(newOriginalText, oMatch.Value, replaceStr);
            }
            newOriginalText = newOriginalText.Replace("**3", "原告被告");
            return newOriginalText;
        }

        /// <summary>
        /// 计算人员信息
        /// </summary>
        /// <param name="elementConfigModel">配置信息</param>
        /// <param name="nodeModel">节点</param>
        /// <param name="listnodemode">节点结合</param>
        /// <param name="listSpNameList">代称集合</param>
        /// <param name="nodem"></param>
        /// <returns></returns>
        public List<ElementSpokeName> GetReplace(ElementConfigModel elementConfigModel, NodeModel nodeModel, List<NodeModel> listnodemode, List<ElementSpokeName> listSpNameList, NodeModel nodem = null)
        {
            spokenamelist = listSpNameList;
            //根据诉讼地位信息匹配
            List<ElementSpokeName> listsp = new List<ElementSpokeName>();
            List<ElementSpokeName> listvalue = new List<ElementSpokeName>();
            string suiDegreeid = elementConfigModel.suitDegreeID;
            if (string.IsNullOrEmpty(suiDegreeid) && nodem != null)
            {
                ElementConfigModel configModel = nodem.ElementConfigModel;
                if (configModel != null)
                {
                    elementConfigModel.suitDegreeID = configModel.suitDegreeID;
                }

            }

            if (elementConfigModel.suitDegreeID.IndexOf(",") > 0)
            {
                List<string> suitdegrrList = elementConfigModel.suitDegreeID.Split(',').ToList();
                foreach (string suit in suitdegrrList)
                {
                    listsp.AddRange(spokenamelist.Where(a => a.ES_SuitDrgreeID == suit).ToList());
                }
            }
            else if (elementConfigModel.suitDegreeID != null && elementConfigModel.suitDegreeID != "")
            {
                listsp.AddRange(spokenamelist.Where(a => a.ES_SuitDrgreeID == elementConfigModel.suitDegreeID).ToList());
            }


            //格式化文本信息处理被告1至5的问题。
            nodeModel.OriginalText = FormatOriginalText(nodeModel.OriginalText, listsp);
            if (listsp.Count > 0)
            {
                /*根据人员诉讼地位获取了人员信息*/
                string oreigetxt = "";
                oreigetxt = nodeModel.OriginalText;

                string fReg = RuleParseClass.GerParseReg("RIU1910251718060001")[0];
                //Regex f = new Regex("原被告|原、被告");
                Regex f = new Regex(fReg);

                oreigetxt = f.Replace(oreigetxt, "原告被告");
                //人员信息加载
                List<string> listname = new List<string>();
                foreach (var item in listsp)
                {
                    listname.Add(item.ES_FullName);
                }

                var query = this.spokenamelist.Where(a => !string.IsNullOrEmpty(a.ES_FullName)).Select(a => a).ToList().Select(r => r.ES_SuitDegreeName + "(?=" + r.ES_FullName + (string.IsNullOrEmpty(r.ES_ShortName) ? "" : "|" + r.ES_ShortName) + ")");
                // var query = this.spokenamelist.Where(a => !string.IsNullOrEmpty(a.ES_FullName)).Select(a => a).ToList().Select(r =>  r.ES_FullName + (string.IsNullOrEmpty(r.ES_ShortName) ? "" : "|" + r.ES_ShortName) );

                var replaceReg = string.Join("|", query.ToList<string>());

                oreigetxt = Regex.Replace(oreigetxt, replaceReg, "");

                //替换简称问题
                foreach (ElementSpokeName elementname in spokenamelist)
                {
                    if (!string.IsNullOrEmpty(elementname.ES_ShortName) && !string.IsNullOrEmpty(elementname.ES_FullName))
                    {
                        if (oreigetxt.IndexOf(elementname.ES_ShortName) > -1)
                        {
                            if (oreigetxt.IndexOf(elementname.ES_FullName) < 0)
                            {
                                oreigetxt = oreigetxt.Replace(elementname.ES_ShortName, elementname.ES_FullName);
                            }
                        }
                    }

                }
                //执行正则
                #region 执行正则提取出人员代称信息

                string IgnoreNames = "小区|的小区|业委会|的业委会|适格|资格|所在|居住地";

                string suitDegreeNameKeyWords = string.Empty;

                string regSuitDegreeIDKeyWords = @"被告=被(?!代)|借款人;原告=原(?!代)";

                foreach (var suitDegreeName in listsp)
                {
                    suitDegreeNameKeyWords += (suitDegreeNameKeyWords != string.Empty) ? "|" + suitDegreeName.ES_SuitDegreeName + "(?!" + IgnoreNames + ")" : suitDegreeName.ES_SuitDegreeName + "(?!" + IgnoreNames + ")";
                    string omatchReg = RuleParseClass.GerParseReg("RIU1910211531160001")[0].Replace("(@{Name})", suitDegreeName.ES_SuitDegreeName);
                    Match omatch = Regex.Match(regSuitDegreeIDKeyWords, omatchReg);
                    if (omatch != null)
                        if (!string.IsNullOrEmpty(omatch.Value))
                            suitDegreeNameKeyWords += "|" + omatch.Value;
                }
                string matchDegreeNameRegexStr = RuleParseClass.GerParseReg("RIU1911111013210001")[0].Replace("@{Name}", suitDegreeNameKeyWords);
                string matchPerNameRegexStr = string.Join("|", listname);
                string matchRegexStr = matchPerNameRegexStr + "|" + matchDegreeNameRegexStr;
                MatchCollection matchArr = Regex.Matches(oreigetxt, matchRegexStr);
                List<ElementSpokeName> listPerson = new List<ElementSpokeName>();
                List<string> Listmatch = new List<string>();
                foreach (Match item in matchArr)
                {
                    Listmatch.Add(item.Value);
                }
                if (Listmatch.Count > 0)
                {
                    Listmatch = Listmatch.Distinct().ToList();
                }
                foreach (string value in Listmatch)
                {
                    IList<ElementSpokeName> matchPerson = GetMatchSpokeManByRoleName(listsp, value);

                    listPerson.AddRange(matchPerson);
                }
                listsp = listPerson;

                if (listsp.Count == 0)
                {
                    listsp = GetSpokerManByJudgeShortName(spokenamelist, oreigetxt);
                }

                #endregion
            }
            if (!string.IsNullOrEmpty(elementConfigModel.matchPersonCondi))
            {
                if (elementConfigModel.matchPersonCondi.IndexOf("ni_sex") > -1)
                {
                    string value = elementConfigModel.matchPersonCondi.Split('=')[1];
                    if (listsp.Count > 0)
                    {
                        listsp = listsp.Where(a => a.ES_Sex == value).ToList();
                    }
                }
            }
            if (!string.IsNullOrEmpty(elementConfigModel.matchPersonMode))
            {
                switch (elementConfigModel.matchPersonMode.ToLower())
                {
                    case "extract":
                        listvalue = listsp;
                        break;
                    case "automatch":
                        listvalue.Add(listsp[0]);
                        break;
                    case "minusextract":
                        listvalue = spokenamelist.Except(listsp).ToList();
                        break;
                    case "combine":
                        listvalue = listsp;
                        break;
                    default:
                        listvalue = listsp;
                        break;
                }
            }
            return listsp.Distinct().ToList();
        }


        public List<ElementSpokeName> GetReplace(List<ElementSpokeName> listSpNameList, string orgtext)
        {

            //spokenamelist = listSpNameList;
            ////根据诉讼地位信息匹配
            List<ElementSpokeName> listsp = new List<ElementSpokeName>();
            listsp = listSpNameList;
            //List<ElementSpokeName> listvalue = new List<ElementSpokeName>();
            //string suiDegreeid = elementConfigModel.suitDegreeID;
            //if (string.IsNullOrEmpty(suiDegreeid) && nodem != null)
            //{
            //    ElementConfigModel configModel = nodem.ElementConfigModel;
            //    if (configModel != null)
            //    {
            //        elementConfigModel.suitDegreeID = configModel.suitDegreeID;
            //    }

            //}

            //if (elementConfigModel.suitDegreeID.IndexOf(",") > 0)
            //{
            //    List<string> suitdegrrList = elementConfigModel.suitDegreeID.Split(',').ToList();
            //    foreach (string suit in suitdegrrList)
            //    {
            //        listsp.AddRange(spokenamelist.Where(a => a.ES_SuitDrgreeID == suit).ToList());
            //    }
            //}
            //else if (elementConfigModel.suitDegreeID != null && elementConfigModel.suitDegreeID != "")
            //{
            //    listsp.AddRange(spokenamelist.Where(a => a.ES_SuitDrgreeID == elementConfigModel.suitDegreeID).ToList());
            //}


            //格式化文本信息处理被告1至5的问题。
            orgtext = FormatOriginalText(orgtext, listsp);
            if (listsp.Count > 0)
            {
                /*根据人员诉讼地位获取了人员信息*/
                string oreigetxt = "";
                oreigetxt = orgtext;

                string fReg = RuleParseClass.GerParseReg("RIU1910251718060001")[0];
                //Regex f = new Regex("原被告|原、被告");
                Regex f = new Regex(fReg);

                oreigetxt = f.Replace(oreigetxt, "原告被告");
                //人员信息加载
                List<string> listname = new List<string>();
                foreach (var item in listsp)
                {
                    listname.Add(item.ES_FullName);
                }

                var query = this.spokenamelist.Where(a => !string.IsNullOrEmpty(a.ES_FullName)).Select(a => a).ToList().Select(r => r.ES_SuitDegreeName + "(?=" + r.ES_FullName + (string.IsNullOrEmpty(r.ES_ShortName) ? "" : "|" + r.ES_ShortName) + ")");
                // var query = this.spokenamelist.Where(a => !string.IsNullOrEmpty(a.ES_FullName)).Select(a => a).ToList().Select(r =>  r.ES_FullName + (string.IsNullOrEmpty(r.ES_ShortName) ? "" : "|" + r.ES_ShortName) );

                var replaceReg = string.Join("|", query.ToList<string>());

                oreigetxt = Regex.Replace(oreigetxt, replaceReg, "");

                //替换简称问题
                foreach (ElementSpokeName elementname in spokenamelist)
                {
                    if (!string.IsNullOrEmpty(elementname.ES_ShortName) && !string.IsNullOrEmpty(elementname.ES_FullName))
                    {
                        if (oreigetxt.IndexOf(elementname.ES_ShortName) > -1)
                        {
                            if (oreigetxt.IndexOf(elementname.ES_FullName) < 0)
                            {
                                oreigetxt = oreigetxt.Replace(elementname.ES_ShortName, elementname.ES_FullName);
                            }
                        }
                    }

                }
                //执行正则
                #region 执行正则提取出人员代称信息

                string IgnoreNames = "小区|的小区|业委会|的业委会|适格|资格|所在|居住地";

                string suitDegreeNameKeyWords = string.Empty;

                string regSuitDegreeIDKeyWords = @"被告=被(?!代)|借款人;原告=原(?!代)";

                foreach (var suitDegreeName in listsp)
                {
                    suitDegreeNameKeyWords += (suitDegreeNameKeyWords != string.Empty) ? "|" + suitDegreeName.ES_SuitDegreeName + "(?!" + IgnoreNames + ")" : suitDegreeName.ES_SuitDegreeName + "(?!" + IgnoreNames + ")";
                    string omatchReg = RuleParseClass.GerParseReg("RIU1910211531160001")[0].Replace("(@{Name})", suitDegreeName.ES_SuitDegreeName);
                    Match omatch = Regex.Match(regSuitDegreeIDKeyWords, omatchReg);
                    if (omatch != null)
                        if (!string.IsNullOrEmpty(omatch.Value))
                            suitDegreeNameKeyWords += "|" + omatch.Value;
                }
                string matchDegreeNameRegexStr = RuleParseClass.GerParseReg("RIU1911111013210001")[0].Replace("@{Name}", suitDegreeNameKeyWords);
                string matchPerNameRegexStr = string.Join("|", listname);
                string matchRegexStr = matchPerNameRegexStr + "|" + matchDegreeNameRegexStr;
                MatchCollection matchArr = Regex.Matches(oreigetxt, matchRegexStr);
                List<ElementSpokeName> listPerson = new List<ElementSpokeName>();
                List<string> Listmatch = new List<string>();
                foreach (Match item in matchArr)
                {
                    Listmatch.Add(item.Value);
                }
                if (Listmatch.Count > 0)
                {
                    Listmatch = Listmatch.Distinct().ToList();
                }
                foreach (string value in Listmatch)
                {
                    IList<ElementSpokeName> matchPerson = GetMatchSpokeManByRoleName(listsp, value);

                    listPerson.AddRange(matchPerson);
                }
                listsp = listPerson;

                if (listsp.Count == 0)
                {
                    listsp = GetSpokerManByJudgeShortName(spokenamelist, oreigetxt);
                }

                #endregion
            }

            return listsp.Distinct().ToList();
        }
        /// <summary>
        /// 根据发言人得到人员集合
        /// </summary>
        /// <param name="relatList">人员集合</param>
        /// <param name="name">发言人名称</param>
        /// <returns></returns>
        public virtual List<ElementSpokeName> GetSpokerManByJudgeShortName(IList<ElementSpokeName> relatList, string name)
        {
            List<ElementSpokeName> matched = new List<ElementSpokeName>();

            List<char> nameList = name.ToCharArray().ToList();

            var spokenFullName = from spoke in relatList
                                 where spoke.ES_FullName != ""
                                 select spoke;
            List<ElementSpokeName> spokerman = spokenFullName.ToList();

            foreach (var item in spokerman)
            {
                List<List<int>> countindex = new List<List<int>>();

                List<char> fullnamelist = item.ES_FullName.ToCharArray().ToList();

                decimal count = nameList.Count / fullnamelist.Count;

                if (count < 1)
                {
                    foreach (var schar in nameList)
                    {
                        List<int> list = fullnamelist.Select
                        (
                         (n, index) => new
                         {
                             n = n,
                             i = index
                         }).Where(a => a.n == schar).Select(a => a.i).ToList();
                        if (list.Count > 0)
                        {
                            countindex.Add(list);
                        }
                    }
                    if (countindex.Count > 0)
                    {
                        bool flag = JudgeIndex(countindex);

                        if (flag)
                        {
                            matched.Add(item);
                            matched = GetSpokerManByShortName(count, matched, name);
                        }

                    }
                }
                else
                {
                    foreach (var schar in fullnamelist)
                    {
                        List<int> list = nameList.Select
                        (
                         (n, index) => new
                         {
                             n = n,
                             i = index
                         }).Where(a => a.n == schar).Select(a => a.i).ToList();
                        if (list.Count > 0)
                        {
                            countindex.Add(list);
                        }
                    }
                    if (countindex.Count > 0)
                    {
                        bool flag = JudgeIndex(countindex);

                        if (flag)
                        {
                            matched.Add(item);
                            matched = GetSpokerManByShortName(count, matched, name);
                        }

                    }
                }
            }
            return matched;
        }

        /// <summary>
        /// 解决保险分公司等匹配不到人员的问题 （逆向匹配等问题 使用简称匹配全称）
        /// </summary>
        /// <param name="relatList">人员集合</param>
        /// <param name="name">简称</param>
        /// <returns></returns>
        public virtual List<ElementSpokeName> GetSpokerManByShortName(decimal count, IList<ElementSpokeName> relatList, string name)
        {
            StringCompute sp = new StringCompute();
            List<Tuple<ElementSpokeName, decimal>> list = new List<Tuple<ElementSpokeName, decimal>>();
            List<ElementSpokeName> retList = new List<ElementSpokeName>();
            foreach (var item in relatList)
            {
                string name1 = RuleParseClass.GetParseRegCodeValue("CE_SuggestDeduceA2", item.ES_FullName);
                string name2 = RuleParseClass.GetParseRegCodeValue("CE_SuggestDeduceA2", name);
                sp.Compute(name1, name2);

                list.Add(new Tuple<ElementSpokeName, decimal>(item, sp.ComputeResult.Rate));
            }
            decimal d = list.Max(a => a.Item2);
            if (count < 1)
            {
                if (d >= (decimal)0.20)
                    return list.Where(a => a.Item2 == d).Select(a => a.Item1).ToList();
                else
                    return new List<ElementSpokeName>();
            }
            else
            {
                if (d >= (decimal)0.95)
                {
                    return list.Where(a => a.Item2 == d).Select(a => a.Item1).ToList();
                }
                else
                {
                    return new List<ElementSpokeName>();
                }
            }
        }

        /// <summary>
        /// 判断
        /// </summary>
        /// <param name="countindex"></param>
        /// <returns></returns>
        public virtual bool JudgeIndex(List<List<int>> countindex)
        {
            bool flag = true;

            for (int i = 0; i < countindex.Count; i++)
            {
                List<int> last = new List<int>();
                List<int> next = new List<int>();
                if (i - 1 > 0)
                {
                    last = countindex[i - 1];
                }
                if (i + 1 < countindex.Count - 1)
                {
                    next = countindex[i + 1];
                }

                if (last.Count > 0 && next.Count > 0)
                {
                    int min = last.Min();
                    int max = next.Max();
                    if (countindex[i].Any(a => a > min) && countindex[i].Any(a => a < max) && min < max)
                    {
                        flag = true;
                    }
                    else
                    {
                        flag = false;
                    }
                }
                else
                {
                    if (last.Count == 0 && next.Count > 0)
                    {
                        int max = next.Max();
                        if (!countindex[i].Any(a => a < max))
                        {
                            flag = false;
                        }
                    }
                    else if (next.Count == 0 && last.Count > 0)
                    {
                        int min = last.Min();
                        if (!countindex[i].Any(a => a > min))
                        {
                            flag = false;
                        }
                    }
                    else
                    {
                        flag = false;
                    }
                }
            }

            return flag;
        }
    }
}
